package com.example.fw;

import static org.junit.Assert.fail;

import java.util.Properties;
import java.util.concurrent.TimeUnit;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;


public class ApplicationManager {
	
	private WebDriver driver;
	public String baseUrl;
	int timeWait;
	private StringBuffer verificationErrors = new StringBuffer();
	
	private Properties properties;
	private AccountHelper account;
	private MailHelper mailHelper;
	private JamesHelper jamesHelper;
	
	public ApplicationManager(Properties properties) {
		this.properties = properties;
	}

	public void stop() {
		driver.quit();
		String verificationErrorString = verificationErrors.toString();
		if (!"".equals(verificationErrorString)) {
			fail(verificationErrorString);
		}
	}
	
	public WebDriver getWebDriver(){
		if (driver == null) {
			String browser = properties.getProperty("browser");
			if("firefox".equals(browser)){
				driver = new FirefoxDriver();
			} else if("ie".equals(browser)){
				driver = new InternetExplorerDriver();
			} else{
				throw new Error("Unsupported brouser: " + browser); 
			}
			baseUrl = properties.getProperty("baseUrl");
			timeWait = Integer.parseInt(properties.getProperty("timeWait"));
			driver.manage().timeouts().implicitlyWait(timeWait, TimeUnit.SECONDS);
			driver.get(baseUrl);
		}
		return driver;
	}

	public AccountHelper getAccountHelper() {
		if (account == null) {
			account = new AccountHelper(this);
		}
		return account;
	}
	
	public String getProperty(String key){
		return properties.getProperty(key);
	}

	public MailHelper getMailHelper() {
		if (mailHelper == null) {
			mailHelper = new MailHelper(this);
		}
		return mailHelper;
	}
	
	public JamesHelper getJamesHelper() {
		if (jamesHelper == null) {
			jamesHelper = new JamesHelper(this);
		}
		return jamesHelper;
	}
}
